import React, { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Space,
  Typography,
  Row,
  Col,
  Checkbox,
  Alert,
  message,
  Divider,
  InputNumber,
  Radio
} from 'antd';
import {
  DatabaseOutlined,
  SaveOutlined,
  PlayCircleOutlined,
  InfoCircleOutlined,
  LinkOutlined,
  BranchesOutlined,
  CodeOutlined,
  KeyOutlined,
  LockOutlined,
  ClockCircleOutlined,
  RobotOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { createScanTaskWithCredentials, CreateScanTaskWithCredentialsRequest, startTask, testDatabaseConnection, DatabaseConnectionTestRequest } from '../../services/api';
import './CreateTask.css';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;

interface FormValues {
  taskType: 'GIT_SOURCE_SCAN' | 'DATABASE_DDL_SCAN';
  sourceDbType: string;
  targetDbType: string;
  aiEnhancementEnabled: boolean;

  // Git配置（仅GIT_SOURCE_SCAN时使用）
  gitRepoUrl?: string;
  gitBranch?: string;
  personalAccessToken?: string;
  credentialExpirationMinutes?: number;

  // 数据库配置（仅DATABASE_DDL_SCAN时使用）
  dbHost?: string;
  dbPort?: number;
  dbName?: string;
  dbSchema?: string;
  dbUsername?: string;
  dbPassword?: string;
  sourceDbVersion?: string;
  oracleConnectionType?: string;
  ddlIncludeViews?: boolean;
  ddlIncludeIndexes?: boolean;
  ddlIncludeConstraints?: boolean;
  ddlTargetTables?: string;
}

const CreateTask: React.FC = () => {
  const [form] = Form.useForm<FormValues>();
  const [loading, setLoading] = useState(false);
  const [selectedTaskType, setSelectedTaskType] = useState<'GIT_SOURCE_SCAN' | 'DATABASE_DDL_SCAN'>('GIT_SOURCE_SCAN');
  const [aiEnhancementEnabled, setAiEnhancementEnabled] = useState<boolean>(false);
  const [detectedGitPlatform, setDetectedGitPlatform] = useState<'GITLAB' | 'GITEE' | 'GITHUB' | null>(null);
  const [testingConnection, setTestingConnection] = useState(false);
  const [connectionTested, setConnectionTested] = useState(false);
  const [connectionTestResult, setConnectionTestResult] = useState<{ success: boolean, message: string } | null>(null);
  const [detectedDatabaseVersion, setDetectedDatabaseVersion] = useState<string | null>(null);
  const navigate = useNavigate();

  // 从仓库地址自动识别Git平台
  const detectGitPlatform = (url: string): 'GITLAB' | 'GITEE' | 'GITHUB' | null => {
    if (!url) return null;

    const lowerUrl = url.toLowerCase();
    if (lowerUrl.includes('github.com')) {
      return 'GITHUB';
    } else if (lowerUrl.includes('gitee.com')) {
      return 'GITEE';
    } else if (lowerUrl.includes('gitlab.com') || lowerUrl.includes('gitlab.')) {
      return 'GITLAB';
    }

    return null;
  };

  // 监听仓库地址变化，自动识别平台
  const handleRepoUrlChange = (url: string) => {
    const platform = detectGitPlatform(url);
    setDetectedGitPlatform(platform);
    form.setFieldsValue({ gitRepoUrl: url });
  };

  // Git 仓库地址校验：必须 http/https 开头，且不能以 .git 结尾
  const validateRepositoryUrl = async (_: any, value?: string) => {
    if (!value || !value.trim()) return Promise.resolve();
    const trimmed = value.trim();
    if (!/^https?:\/\//i.test(trimmed)) {
      return Promise.reject(new Error('必须输入以 http 或 https 开头的仓库地址'));
    }
    if (/\.git\s*$/i.test(trimmed)) {
      return Promise.reject(new Error('仓库地址不能以 .git 结尾，请去掉 .git 后缀'));
    }
    return Promise.resolve();
  };

  // 测试数据库连接
  const handleTestDatabaseConnection = async () => {
    const values = form.getFieldsValue();

    // 验证必要字段
    if (!values.dbHost?.trim() || !values.dbUsername?.trim() || !values.dbPassword?.trim() || !values.dbName?.trim()) {
      message.error('请先填写完整的数据库连接信息');
      return;
    }

    setTestingConnection(true);
    setConnectionTestResult(null);

    try {
      // 使用新的API函数调用后端测试连接接口
      const request: DatabaseConnectionTestRequest = {
        host: values.dbHost,
        port: values.dbPort || 3306,
        database: values.dbName,
        schema: values.dbSchema,
        username: values.dbUsername,
        password: values.dbPassword,
        dbType: values.sourceDbType,
        oracleConnectionType: values.oracleConnectionType || 'SERVICE_NAME'
      };

      const result = await testDatabaseConnection(request);

      if (result.success) {
        setConnectionTested(true);
        setConnectionTestResult({ success: true, message: '数据库连接成功！' });

        // 保存检测到的数据库版本信息
        if (result.data?.databaseVersion) {
          setDetectedDatabaseVersion(result.data.normalizedVersion || result.data.databaseVersion);
          form.setFieldsValue({ sourceDbVersion: result.data.normalizedVersion || result.data.databaseVersion });
        }

        message.success('数据库连接成功！' + (result.data?.databaseVersion ? ` 检测到版本: ${result.data.databaseVersion}` : ''));
      } else {
        setConnectionTested(false);
        setConnectionTestResult({ success: false, message: result.message || '连接失败' });
        setDetectedDatabaseVersion(null);
        message.error(result.message || '数据库连接失败');
      }
    } catch (error: any) {
      setConnectionTested(false);
      setConnectionTestResult({ success: false, message: '网络请求失败' });
      message.error('测试连接失败：' + (error.message || '网络错误'));
    } finally {
      setTestingConnection(false);
    }
  };

  // 重置连接测试状态（当数据库配置变化时）
  const resetConnectionTest = () => {
    setConnectionTested(false);
    setConnectionTestResult(null);
    setDetectedDatabaseVersion(null);
  };

  // 生成任务名称的辅助函数
  const generateTaskName = (values: Partial<FormValues>): string => {
    const now = new Date();
    const dateStr = now.toISOString().slice(0, 19).replace(/[T:-]/g, '').slice(0, 14);

    const taskTypeMap: Record<string, string> = {
      'GIT_SOURCE_SCAN': 'Git源码扫描',
      'DATABASE_DDL_SCAN': '数据库DDL扫描'
    };

    const sourceDbMap: Record<string, string> = {
      'ORACLE': 'Oracle',
      'MYSQL': 'MySQL'
    };

    const targetDbMap: Record<string, string> = {
      'GOLDENDB': 'GoldenDB'
    };

    const taskTypeName = taskTypeMap[values.taskType!] || '扫描';
    const sourceDb = sourceDbMap[values.sourceDbType!] || values.sourceDbType;
    const targetDb = targetDbMap[values.targetDbType!] || values.targetDbType;

    return `${taskTypeName}_${sourceDb}到${targetDb}_${dateStr}`;
  };

  // 生成任务描述的辅助函数
  const generateTaskDescription = (values: Partial<FormValues>): string => {
    const taskTypeMap: Record<string, string> = {
      'GIT_SOURCE_SCAN': 'Git源码仓库中的SQL语句进行兼容性分析',
      'DATABASE_DDL_SCAN': '数据库DDL结构进行兼容性分析'
    };

    const sourceDbMap: Record<string, string> = {
      'ORACLE': 'Oracle',
      'MYSQL': 'MySQL'
    };

    const targetDbMap: Record<string, string> = {
      'GOLDENDB': 'GoldenDB'
    };

    const taskTypeDesc = taskTypeMap[values.taskType!] || '数据进行兼容性分析';
    const sourceDb = sourceDbMap[values.sourceDbType!] || values.sourceDbType;
    const targetDb = targetDbMap[values.targetDbType!] || values.targetDbType;

    let description = `对${taskTypeDesc}，分析从${sourceDb}到${targetDb}的兼容性问题。`;

    if (values.taskType === 'DATABASE_DDL_SCAN' && values.sourceDbVersion) {
      description += `\n源数据库版本：${values.sourceDbVersion}`;
    }

    if (values.taskType === 'GIT_SOURCE_SCAN' && values.gitRepoUrl) {
      const repoName = values.gitRepoUrl.split('/').pop()?.replace('.git', '') || '代码仓库';
      description += `\n扫描仓库：${repoName}`;
      if (values.gitBranch) {
        description += `\n分支：${values.gitBranch}`;
      }
    }

    return description;
  };

  const handleSubmit = async (values: FormValues) => {
    // 自动生成任务名称和描述
    const taskName = generateTaskName(values);
    const description = generateTaskDescription(values);

    // 数据库扫描类型必须先测试连接
    if (values.taskType === 'DATABASE_DDL_SCAN' && !connectionTested) {
      message.error('请先测试数据库连接并确保连接成功');
      return;
    }

    try {
      setLoading(true);

      // 验证任务类型特定的字段
      if (values.taskType === 'GIT_SOURCE_SCAN') {
        if (!values.personalAccessToken?.trim()) {
          message.error('Git源码扫描需要提供个人访问令牌');
          setLoading(false);
          return;
        }
        if (!values.gitRepoUrl?.trim()) {
          message.error('Git源码扫描需要提供仓库地址');
          setLoading(false);
          return;
        }
      } else if (values.taskType === 'DATABASE_DDL_SCAN') {
        if (!values.dbHost?.trim() || !values.dbUsername?.trim() || !values.dbPassword?.trim()) {
          message.error('数据库DDL扫描需要完整的数据库连接信息');
          setLoading(false);
          return;
        }
      }

      const request: CreateScanTaskWithCredentialsRequest = {
        taskName,
        taskType: values.taskType,
        description,
        branchName: values.taskType === 'GIT_SOURCE_SCAN' ? (values.gitBranch || 'master') : undefined,
        aiEnhancementEnabled: values.aiEnhancementEnabled,

        // AI筛选配置
        config: {
          sourceDbType: values.sourceDbType,
          targetDbType: values.targetDbType,
          taskType: values.taskType,
          aiEnhancementEnabled: values.aiEnhancementEnabled,
          // Git相关配置
          ...(values.taskType === 'GIT_SOURCE_SCAN' && {
            gitAuthMode: 'PERSONAL_TOKEN',
            gitPlatform: detectedGitPlatform || 'GITLAB',
            repositoryUrl: values.gitRepoUrl,
            branchName: values.gitBranch || 'master',
          }),
          // 数据库相关配置
          ...(values.taskType === 'DATABASE_DDL_SCAN' && {
            databaseHost: values.dbHost,
            databasePort: values.dbPort,
            databaseName: values.dbName,
            databaseSchema: values.dbSchema,
            databaseUsername: values.dbUsername,
            databaseVersion: values.sourceDbVersion,
            oracleConnectionType: values.oracleConnectionType || 'SERVICE_NAME',
            ddlExtractionOptions: {
              includeViews: values.ddlIncludeViews || false,
              includeIndexes: values.ddlIncludeIndexes || false,
              includeConstraints: values.ddlIncludeConstraints || false,
              targetTables: values.ddlTargetTables ? values.ddlTargetTables.split(',').map(t => t.trim()) : []
            }
          })
        },

        // Git相关凭据
        ...(values.taskType === 'GIT_SOURCE_SCAN' && {
          gitAuthMode: 'PERSONAL_TOKEN',
          gitPlatform: detectedGitPlatform || 'GITLAB',
          gitRepositoryUrl: values.gitRepoUrl,
          personalAccessToken: values.personalAccessToken,
          credentialExpirationMinutes: values.credentialExpirationMinutes || 60,
        }),

        // 数据库相关凭据
        ...(values.taskType === 'DATABASE_DDL_SCAN' && {
          enableDatabaseScan: true,
          databaseHost: values.dbHost,
          databasePort: values.dbPort,
          databaseName: values.dbName,
          databaseSchema: values.dbSchema,
          databaseUsername: values.dbUsername,
          databasePassword: values.dbPassword,
          oracleConnectionType: values.oracleConnectionType || 'SERVICE_NAME'
        })
      };

      const response = await createScanTaskWithCredentials(request);

      if (response.success) {
        message.success('扫描任务创建成功！');

        // 立即跳转到任务详情页面
        navigate(`/tasks/${response.data.id}`);

        // 异步启动任务，不等待结果
        startTask(response.data.id)
          .then(() => {
            message.success('任务已成功启动！');
          })
          .catch((startError: any) => {
            console.error('启动任务失败:', startError);
            message.warning(`任务启动失败: ${startError.message || '请在任务详情页手动启动'}`);
          });

      } else {
        message.error(response.message || '创建任务失败');
      }
    } catch (error: any) {
      console.error('创建任务失败:', error);
      message.error(error.message || '创建任务失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const getRepositoryUrlExample = (): string => {
    if (detectedGitPlatform === 'GITHUB') {
      return 'https://github.com/username/repository';
    } else if (detectedGitPlatform === 'GITEE') {
      return 'https://gitee.com/username/repository';
    } else {
      return 'https://gitlab.com/username/repository';
    }
  };

  const getTokenHelpText = (): string => {
    if (detectedGitPlatform === 'GITHUB') {
      return '在GitHub中访问 Settings > Developer settings > Personal access tokens > Generate new token，选择 repo 权限';
    } else if (detectedGitPlatform === 'GITEE') {
      return '在Gitee中访问 设置 > 私人令牌 > 生成新令牌，选择 projects 权限';
    } else if (detectedGitPlatform === 'GITLAB') {
      return '在GitLab中访问 个人资料 > 访问令牌 > 创建个人访问令牌，选择 read_repository 权限';
    } else {
      return '请先输入仓库地址，系统将自动识别平台类型并提供相应的令牌获取指南';
    }
  };

  const handleTaskTypeChange = (taskType: 'GIT_SOURCE_SCAN' | 'DATABASE_DDL_SCAN') => {
    setSelectedTaskType(taskType);
    form.setFieldsValue({ taskType });

    // 清除其他类型的字段
    if (taskType === 'GIT_SOURCE_SCAN') {
      // 清除数据库相关字段
      form.setFieldsValue({
        dbHost: undefined,
        dbPort: undefined,
        dbName: undefined,
        dbSchema: undefined,
        dbUsername: undefined,
        dbPassword: undefined,
        sourceDbVersion: undefined,
        ddlIncludeViews: undefined,
        ddlIncludeIndexes: undefined,
        ddlIncludeConstraints: undefined,
        ddlTargetTables: undefined
      });
      // 重置连接测试状态
      resetConnectionTest();
    } else {
      // 清除Git相关字段
      form.setFieldsValue({
        gitRepoUrl: undefined,
        gitBranch: undefined,
        personalAccessToken: undefined,
        credentialExpirationMinutes: undefined
      });
      // 重置平台检测
      setDetectedGitPlatform(null);
    }
  };

  const handleAiEnhancementChange = (checked: boolean) => {
    setAiEnhancementEnabled(checked);
    form.setFieldsValue({ aiEnhancementEnabled: checked });
  };

  return (
    <div className="create-task">
      <div className="page-header">
        <Title level={3}>
          创建扫描任务
        </Title>
        <Paragraph type="secondary">
          创建SQL兼容性扫描任务，支持Git源码分析和数据库DDL扫描两种模式。任务名称和描述将根据配置自动生成。
        </Paragraph>
      </div>

      <Row gutter={[24, 24]}>
        <Col xs={24} lg={16}>
          <Card title="任务配置" className="task-form-card">
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
              initialValues={{
                taskType: 'GIT_SOURCE_SCAN',
                sourceDbType: 'ORACLE',
                targetDbType: 'GOLDENDB',
                aiEnhancementEnabled: false,
                gitBranch: 'master',
                dbPort: 3306,
                credentialExpirationMinutes: 60,
                oracleConnectionType: 'SERVICE_NAME',
                ddlIncludeViews: true,
                ddlIncludeIndexes: true,
                ddlIncludeConstraints: true
              }}
            >
              {/* 基础信息 */}
              <Title level={5}>基础信息</Title>

              {/* 任务类型选择 */}
              {/* 任务类型选择 - 使用隐藏字段存储值 */}
              <Form.Item name="taskType" hidden>
                <Input />
              </Form.Item>

              <Form.Item
                label="扫描类型"
                rules={[{ required: true, message: '请选择扫描类型' }]}
              >
                <Row gutter={16}>
                  <Col span={12}>
                    <Card
                      hoverable
                      className={`task-type-card ${selectedTaskType === 'GIT_SOURCE_SCAN' ? 'selected' : ''}`}
                      onClick={() => handleTaskTypeChange('GIT_SOURCE_SCAN')}
                      style={{
                        borderColor: selectedTaskType === 'GIT_SOURCE_SCAN' ? '#52c41a' : '#d9d9d9',
                        backgroundColor: selectedTaskType === 'GIT_SOURCE_SCAN' ? '#f6ffed' : '#fafafa',
                        cursor: 'pointer'
                      }}
                    >
                      <Space direction="vertical" style={{ width: '100%' }}>
                        <Space>
                          <CodeOutlined style={{ color: selectedTaskType === 'GIT_SOURCE_SCAN' ? '#52c41a' : '#999' }} />
                          <Text strong style={{ color: selectedTaskType === 'GIT_SOURCE_SCAN' ? '#52c41a' : '#000' }}>Git源码扫描</Text>
                        </Space>
                        <Text type="secondary" style={{ fontSize: '12px' }}>
                          分析MyBatis、JPA、JDBC等框架中的SQL语句，包括XML文件、Java注解中的SQL语句
                        </Text>
                      </Space>
                    </Card>
                  </Col>
                  <Col span={12}>
                    <Card
                      hoverable
                      className={`task-type-card ${selectedTaskType === 'DATABASE_DDL_SCAN' ? 'selected' : ''}`}
                      onClick={() => handleTaskTypeChange('DATABASE_DDL_SCAN')}
                      style={{
                        borderColor: selectedTaskType === 'DATABASE_DDL_SCAN' ? '#fa8c16' : '#d9d9d9',
                        backgroundColor: selectedTaskType === 'DATABASE_DDL_SCAN' ? '#fff7e6' : '#fafafa',
                        cursor: 'pointer'
                      }}
                    >
                      <Space direction="vertical" style={{ width: '100%' }}>
                        <Space>
                          <DatabaseOutlined style={{ color: selectedTaskType === 'DATABASE_DDL_SCAN' ? '#fa8c16' : '#999' }} />
                          <Text strong style={{ color: selectedTaskType === 'DATABASE_DDL_SCAN' ? '#fa8c16' : '#000' }}>数据库DDL扫描</Text>
                        </Space>
                        <Text type="secondary" style={{ fontSize: '12px' }}>
                          连接数据库分析表结构、字段类型、约束等
                        </Text>
                      </Space>
                    </Card>
                  </Col>
                </Row>
              </Form.Item>

              {/* AI增强配置 */}
              <Form.Item
                name="aiEnhancementEnabled"
                label="AI增强分析"
                valuePropName="checked"
                extra="开启后将使用AI对检测到的问题进行深度分析和优化建议（系统将自动应用全局配置参数）"
              >
                <Checkbox onChange={(e) => handleAiEnhancementChange(e.target.checked)}>
                  <Space>
                    <RobotOutlined style={{ color: aiEnhancementEnabled ? '#1890ff' : '#999' }} />
                    <span>启用AI增强分析</span>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      （智能优化、深度分析）
                    </Text>
                  </Space>
                </Checkbox>
              </Form.Item>

              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    name="sourceDbType"
                    label="源数据库类型"
                    rules={[{ required: true, message: '请选择源数据库类型' }]}
                  >
                    <Select>
                      <Option value="ORACLE">Oracle</Option>
                      <Option value="MYSQL">MySQL</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="targetDbType"
                    label="目标数据库类型"
                    rules={[{ required: true, message: '请选择目标数据库类型' }]}
                  >
                    <Select>
                      <Option value="GOLDENDB">GoldenDB</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>

              <Divider />

              {/* Git平台配置 */}
              {selectedTaskType === 'GIT_SOURCE_SCAN' && (
                <div className="config-section">
                  <Title level={5}>
                    <KeyOutlined /> Git仓库配置
                  </Title>

                  <Alert
                    message="安全说明"
                    description="个人访问令牌仅在任务执行期间临时存储，任务完成后自动清理，不会持久化保存；数据库密码仅用于建立临时连接，不会在服务器端持久化存储。请合理的设置令牌过期时间，在有效期内可以重试任务。"
                    type="success"
                    showIcon
                    style={{ marginBottom: 16 }}
                  />

                  {/* 显示检测到的Git平台 */}
                  {detectedGitPlatform && (
                    <Alert
                      message={`已检测到Git平台：${detectedGitPlatform === 'GITHUB' ? 'GitHub' : detectedGitPlatform === 'GITEE' ? 'Gitee' : 'GitLab'}`}
                      type="info"
                      showIcon
                      style={{ marginBottom: 16 }}
                    />
                  )}

                  <Form.Item
                    name="gitRepoUrl"
                    label="仓库地址"
                    rules={[
                      { required: true, message: '请输入Git仓库地址' },
                      { validator: validateRepositoryUrl }
                    ]}
                    extra={`例如：${getRepositoryUrlExample()}。系统将自动识别平台类型`}
                  >
                    <Input
                      prefix={<LinkOutlined />}
                      placeholder={getRepositoryUrlExample()}
                      onChange={(e) => handleRepoUrlChange(e.target.value)}
                    />
                  </Form.Item>

                  <Row gutter={16}>
                    <Col span={12}>
                      <Form.Item
                        name="gitBranch"
                        label="分支名称"
                        rules={[{ required: true, message: '请输入分支名称' }]}
                      >
                        <Input
                          prefix={<BranchesOutlined />}
                          placeholder="master"
                        />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        name="credentialExpirationMinutes"
                        label="令牌过期时间（分钟）"
                        rules={[{ required: true, message: '请输入过期时间' }]}
                      >
                        <InputNumber
                          min={10}
                          max={480}
                          placeholder="60"
                          prefix={<ClockCircleOutlined />}
                          style={{ width: '100%' }}
                        />
                      </Form.Item>
                    </Col>
                  </Row>

                  <Form.Item
                    name="personalAccessToken"
                    label="个人访问令牌"
                    rules={[{ required: true, message: '请输入个人访问令牌' }]}
                    extra={getTokenHelpText()}
                  >
                    <Input.Password
                      prefix={<LockOutlined />}
                      placeholder="请输入个人访问令牌"
                      visibilityToggle
                    />
                  </Form.Item>
                </div>
              )}

              {/* 数据库配置 */}
              {selectedTaskType === 'DATABASE_DDL_SCAN' && (
                <div className="config-section">
                  <Title level={5}>
                    <DatabaseOutlined /> 数据库连接配置
                  </Title>

                  <Alert
                    message="安全提示"
                    description="数据库密码仅用于建立临时连接，不会在服务器端持久化存储"
                    type="info"
                    showIcon
                    style={{ marginBottom: 16 }}
                  />

                  <Row gutter={16}>
                    <Col span={16}>
                      <Form.Item
                        name="dbHost"
                        label="主机地址"
                        rules={[{ required: true, message: '请输入数据库主机地址' }]}
                      >
                        <Input placeholder="localhost 或 IP地址" onChange={resetConnectionTest} />
                      </Form.Item>
                    </Col>
                    <Col span={8}>
                      <Form.Item
                        name="dbPort"
                        label="端口"
                        rules={[{ required: true, message: '请输入端口号' }]}
                      >
                        <InputNumber
                          placeholder="3306"
                          min={1}
                          max={65535}
                          style={{ width: '100%' }}
                          onChange={resetConnectionTest}
                        />
                      </Form.Item>
                    </Col>
                  </Row>

                  <Row gutter={16}>
                    <Col span={12}>
                      <Form.Item
                        name="dbName"
                        label="数据库名"
                        rules={[{ required: true, message: '请输入数据库名' }]}
                        extra={form.getFieldValue('sourceDbType') === 'ORACLE' ?
                          '填写 SERVICE_NAME 或 SID（根据下方选择）' : '数据库名称'}
                      >
                        <Input placeholder="数据库名称" onChange={resetConnectionTest} />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        name="dbSchema"
                        label="Schema"
                        extra="可选，用于指定特定的数据库模式"
                      >
                        <Input placeholder="schema名称（可选）" onChange={resetConnectionTest} />
                      </Form.Item>
                    </Col>
                  </Row>

                  {/* Oracle 连接方式选择 */}
                  {form.getFieldValue('sourceDbType') === 'ORACLE' && (
                    <Form.Item
                      name="oracleConnectionType"
                      label="Oracle 连接方式"
                      extra="SERVICE_NAME 适用于 Oracle 9i+（推荐），SID 适用于旧版本或特殊配置"
                    >
                      <Radio.Group onChange={resetConnectionTest}>
                        <Radio value="SERVICE_NAME">SERVICE_NAME（推荐）</Radio>
                        <Radio value="SID">SID（旧版）</Radio>
                      </Radio.Group>
                    </Form.Item>
                  )}

                  <Row gutter={16}>
                    <Col span={12}>
                      <Form.Item
                        name="dbUsername"
                        label="用户名"
                        rules={[{ required: true, message: '请输入数据库用户名' }]}
                      >
                        <Input placeholder="数据库用户名" onChange={resetConnectionTest} />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        name="dbPassword"
                        label="密码"
                        rules={[{ required: true, message: '请输入数据库密码' }]}
                        extra="密码仅用于建立连接，不会保存到服务器"
                      >
                        <Input.Password
                          placeholder="数据库密码"
                          visibilityToggle
                          onChange={resetConnectionTest}
                        />
                      </Form.Item>
                    </Col>
                  </Row>

                  {/* 测试连接按钮 */}
                  <Form.Item style={{ marginBottom: 24 }}>
                    <Space>
                      <Button
                        type="default"
                        onClick={handleTestDatabaseConnection}
                        loading={testingConnection}
                        disabled={testingConnection}
                        icon={<DatabaseOutlined />}
                      >
                        {testingConnection ? '正在测试连接...' : '测试连接'}
                      </Button>
                      {connectionTestResult && (
                        <Text type={connectionTestResult.success ? 'success' : 'danger'}>
                          {connectionTestResult.message}
                        </Text>
                      )}
                    </Space>
                  </Form.Item>

                  {/* 数据库版本显示 */}
                  <Form.Item
                    name="sourceDbVersion"
                    label="数据库版本"
                    extra="版本信息将在测试连接成功后自动检测"
                  >
                    <Input
                      placeholder={connectionTested && detectedDatabaseVersion ? `自动检测: ${detectedDatabaseVersion}` : "请先测试连接以检测数据库版本"}
                      disabled
                      value={detectedDatabaseVersion || ''}
                      suffix={
                        detectedDatabaseVersion ? (
                          <Space>
                            <InfoCircleOutlined style={{ color: '#52c41a' }} />
                            <Text style={{ color: '#52c41a', fontSize: '12px' }}>自动检测</Text>
                          </Space>
                        ) : null
                      }
                    />
                  </Form.Item>

                  {/* DDL提取选项 */}
                  <Title level={5} style={{ marginTop: 24 }}>DDL提取选项</Title>
                  <Row gutter={16}>
                    <Col span={8}>
                      <Form.Item name="ddlIncludeViews" valuePropName="checked">
                        <Checkbox>包含视图</Checkbox>
                      </Form.Item>
                    </Col>
                    <Col span={8}>
                      <Form.Item name="ddlIncludeIndexes" valuePropName="checked">
                        <Checkbox>包含索引</Checkbox>
                      </Form.Item>
                    </Col>
                    <Col span={8}>
                      <Form.Item name="ddlIncludeConstraints" valuePropName="checked">
                        <Checkbox>包含约束</Checkbox>
                      </Form.Item>
                    </Col>
                  </Row>

                  <Form.Item
                    name="ddlTargetTables"
                    label="目标表名"
                    extra="指定要扫描的表名，多个表名用逗号分隔。留空则扫描所有表"
                  >
                    <Input placeholder="例如：users,orders,products" />
                  </Form.Item>
                </div>
              )}

              {/* 提交按钮 */}
              <Form.Item style={{ marginTop: 32 }}>
                <Space size="middle">
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={loading}
                    icon={<PlayCircleOutlined />}
                    size="large"
                  >
                    创建并启动任务
                  </Button>
                  <Button
                    icon={<SaveOutlined />}
                    size="large"
                    onClick={() => form.submit()}
                    disabled={loading}
                  >
                    仅保存任务
                  </Button>
                  <Button
                    size="large"
                    onClick={() => navigate('/dashboard')}
                  >
                    取消
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Card>
        </Col>

        {/* 右侧说明 */}
        <Col xs={24} lg={8}>
          {selectedTaskType === 'GIT_SOURCE_SCAN' ? (
            <Card title="个人访问令牌获取指南" size="small">
              <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                <Alert
                  message="GitLab"
                  description={
                    <div>
                      <div>1. 登录GitLab，进入个人资料</div>
                      <div>2. 点击"访问令牌"</div>
                      <div>3. 创建个人访问令牌</div>
                      <div>4. 选择"read_repository"权限</div>
                      <div>5. 复制生成的令牌</div>
                    </div>
                  }
                  type="info"
                  showIcon
                />


              </Space>
            </Card>
          ) : (
            <Card title="数据库版本选择指南" size="small">
              <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                <Alert
                  message="MySQL版本特性"
                  description={
                    <div>
                      <div><strong>MySQL 5.7:</strong> 支持JSON类型、生成列</div>
                      <div><strong>MySQL 8.0+:</strong> 支持窗口函数、检查约束、角色管理</div>
                    </div>
                  }
                  type="info"
                  showIcon
                />

                <Alert
                  message="Oracle版本特性"
                  description={
                    <div>
                      <div><strong>Oracle 11g:</strong> 基础功能、虚拟列</div>
                      <div><strong>Oracle 12c:</strong> 容器数据库、身份列</div>
                      <div><strong>Oracle 19c+:</strong> 更多数据类型、增强安全性</div>
                    </div>
                  }
                  type="success"
                  showIcon
                />
              </Space>
            </Card>
          )}

          <Card
            title={<><InfoCircleOutlined /> 注意事项</>}
            size="small"
            style={{ marginTop: 16 }}
          >
            <ul style={{ marginBottom: 0, paddingLeft: 20, fontSize: '13px' }}>
              <li>
                <Text>
                  <strong>AI增强说明：</strong>
                  系统已预配置AI参数（严重性阈值、处理数量限制、超时时间），默认使用规则引擎快速分析，可选择启用AI增强进行智能优化和深度分析
                </Text>
              </li>
              {selectedTaskType === 'GIT_SOURCE_SCAN' ? (
                <>
                  <li>个人访问令牌仅在任务执行期间使用</li>
                  <li>令牌在指定时间后自动过期，默认60分钟</li>
                  <li>支持MyBatis、JPA、JDBC等框架SQL分析</li>
                  <li>大型项目扫描可能需要较长时间</li>
                </>
              ) : (
                <>
                  <li>数据库连接信息不会持久化存储</li>
                  <li>请确保网络能够访问目标数据库</li>
                  <li>建议使用只读权限的数据库用户</li>
                  <li>版本选择影响兼容性分析的准确性</li>
                </>
              )}
              <li>所有凭据在任务完成后自动清理</li>
            </ul>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default CreateTask;